package com.recharge.service.impl;

import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.recharge.domain.vo.GoodsMerchantDO;
import com.recharge.service.GoodsMerchantService;
import com.recharge.service.GoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.util.BeanUtilsExtends;
import com.recharge.common.util.Constant;
import com.recharge.core.entity.GoodsEntity;
import com.recharge.core.entity.GoodsProviderEntity;
import com.recharge.core.mapper.GoodsProviderMapper;
import com.recharge.domain.query.GoodsProviderQueryDO;
import com.recharge.domain.vo.GoodsDO;
import com.recharge.domain.vo.GoodsProviderDO;
import com.recharge.service.GoodsProviderService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * <p>
 * 商品与供应商关联 服务实现类
 * </p>
 *
 * @author reagan
 * @since 2020-08-19
 */
@Service
public class GoodsProviderServiceImpl extends ServiceImpl<GoodsProviderMapper, GoodsProviderEntity> implements GoodsProviderService {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsMerchantService goodsMerchantService;

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    @Override
    public ResultDO addBatch(GoodsProviderDO param) {
        ResultDO result = new ResultSupport();
        if(param.getParamArray() == null || param.getParamArray().length <= 0){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_GET_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_GET_ERROR.getCode() + " msg" + ErrorCode.PARAM_GET_ERROR.getMsg());
            return result;
        }

        List<GoodsProviderEntity> list = new ArrayList<GoodsProviderEntity>();
        List<GoodsDO> goodsList = new ArrayList<GoodsDO>();

        Arrays.stream(param.getParamArray()).forEach( goodsIdArray ->{
            GoodsProviderEntity  entity = new GoodsProviderEntity();
            BeanUtilsExtends.copy(entity, param);
            entity.setCreateDate(Calendar.getInstance().getTime());
            entity.setModifiDate(entity.getCreateDate());
            entity.setModifier(entity.getCreator());
            entity.setGoodsId(goodsIdArray[0]);
            //设置lastDiscount 为这次批量修改的结果
            entity.setAfterCostDiscount(param.getCostDiscount());
            if(goodsIdArray.length == 2){
                entity.setProviderGoodsNo(goodsIdArray[1]);
            }
            entity.setId(null);
            list.add(entity);

            GoodsDO goods = new GoodsDO();
            goods.setId(goodsIdArray[0]);
            goodsList.add(goods);
        });

//        //判断折扣是否通过
//        result = checkDiscount(result, goodsList, param.getCostDiscount(), param.getLossType());
//        if(!result.isSuccess()){
//            return result;
//        }

        boolean res = false;
        try {
            res = this.saveBatch(list);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_ADD_RELATION_PROVIDER_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_ADD_RELATION_PROVIDER_ERROR.getCode() + " msg" + ErrorCode.GOODS_ADD_RELATION_PROVIDER_ERROR.getMsg());
            return result;
        }
        return result;
    }

    public ResultDO get(String id) {

        ResultDO result = new ResultSupport();
        GoodsProviderEntity entity = null;

        try {
            entity = this.getById(id);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        GoodsProviderDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    public ResultDO getProviderGoodsId(String goodsId) {

        ResultDO result = new ResultSupport();

        List<Map<String, Object>> list = null;

        try {
            list = this.baseMapper.selectProviderByGoodsId(goodsId);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        if(list.size() == 0) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.API_GOODS_NOT_EXITE_ERROR);
            return result;
        }

        result.setModel(ResultDO.FIRST_MODEL_KEY, list);

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO edit(GoodsProviderDO domain) {

        GoodsProviderEntity entity = new GoodsProviderEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setModifiDate(Calendar.getInstance().getTime());

        if(entity.getCostDiscount() != null){
            result = this.get(entity.getId());
            if (!result.isSuccess()) {
                logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                return result;
            }
            GoodsProviderDO goodsProvider = (GoodsProviderDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
            List<GoodsDO> goodsList = new ArrayList<>();
            GoodsDO goodsDO = new GoodsDO();
            goodsDO.setId(goodsProvider.getGoodsId());
            goodsList.add(goodsDO);
            //判断折扣是否通过
            result = checkDiscount(result, goodsList, entity.getCostDiscount(), goodsProvider.getLossType());
            if(!result.isSuccess()){
                return result;
            }
        }

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_EDIT_RELATION_PROVIDER_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_EDIT_RELATION_PROVIDER_ERROR.getCode() + " msg" + ErrorCode.GOODS_EDIT_RELATION_PROVIDER_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO remove(String providerId, String goodsId, String modifier) {
        ResultDO result = new ResultSupport();

        GoodsProviderEntity entity = new GoodsProviderEntity();

        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setIsDelete(Constant.IS_DELETE);
        boolean res = false;
        try {
            res = this.update(entity, Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getProviderId, providerId).eq(GoodsProviderEntity::getGoodsId, goodsId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.GOODS_DELETE_RELATION_PROVIDER_ERROR);
            logger.debug("error code：" + ErrorCode.GOODS_DELETE_RELATION_PROVIDER_ERROR.getCode() + " msg" + ErrorCode.GOODS_DELETE_RELATION_PROVIDER_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO removeBatch(String providerId, String goodsIds, String modifier) {
        ResultDO result = new ResultSupport();
        GoodsProviderEntity entity = new GoodsProviderEntity();
        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setIsDelete(Constant.IS_DELETE);
        try {
            String[] goodsArray = goodsIds.split(",");
            for (String goodsId : goodsArray) {
                result = this.remove(providerId, goodsId, modifier);
                if(!result.isSuccess()){
                    throw new Exception();
                }
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO removeByGoodsId(String goodId, String modifier) {

        ResultDO result = new ResultSupport();

        GoodsProviderEntity entity = new GoodsProviderEntity();

        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setIsDelete(Constant.IS_DELETE);
        boolean res = false;
        try {
            res = this.update(entity, Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getGoodsId, goodId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    @Override
    public ResultDO removeByProviderId(String providerId, String modifier) {
        ResultDO result = new ResultSupport();

        GoodsProviderEntity entity = new GoodsProviderEntity();

        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);
        entity.setIsDelete(Constant.IS_DELETE);
        boolean res = false;
        try {
            res = this.update(entity, Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getProviderId, providerId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO updateCostDiscountBatch(String groupId, String providerId, Float costDiscount, Integer priority, String modifier) {
        GoodsProviderEntity entity = new GoodsProviderEntity();

        ResultDO result = new ResultSupport();
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        result = goodsService.findByGroupId(groupId);
        if(!result.isSuccess()){
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

        List<GoodsDO> goodsList = (List<GoodsDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);

        if(goodsList == null){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        entity.setModifiDate(Calendar.getInstance().getTime());
        entity.setModifier(modifier);

        if(costDiscount != null){
            entity.setCostDiscount(costDiscount);
            //判断折扣是否通过
            result = checkDiscount(result, goodsList, entity.getCostDiscount(), 0);
            if(!result.isSuccess()){
                return result;
            }
        }
        if(priority != null){
            entity.setPriority(priority);
        }

        try {
            for (GoodsDO goods : goodsList) {
                //设置lastDiscount 为这次批量修改的结果
                entity.setAfterCostDiscount(costDiscount);
                baseMapper.update(entity, Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getProviderId, providerId).eq(GoodsProviderEntity::getGoodsId, goods.getId()));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    @Override
    public ResultDO updateStatus(String providerId, String goodsIds, Integer status, String modifier) {
        GoodsProviderEntity entity = new GoodsProviderEntity();
        ResultDO result = new ResultSupport();
        if(StringUtils.isEmpty(providerId) || (status != Constant.MERCHANT_GOODS_GROUP_STATUS_1 && status != Constant.MERCHANT_GOODS_GROUP_STATUS_2)){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_GET_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_GET_ERROR.getCode() + " msg" + ErrorCode.PARAM_GET_ERROR.getMsg());
            return result;
        }

        String[] goodsIdArray = goodsIds.split(",");
        entity.setStatus(status);
        try {
            for (String goodsId : goodsIdArray) {
                baseMapper.update(entity, Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getProviderId, providerId).eq(GoodsProviderEntity::getGoodsId, goodsId));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO updateStatus(String providerId, Integer status, String modifier) {
        GoodsProviderEntity entity = new GoodsProviderEntity();
        ResultDO result = new ResultSupport();
        if(StringUtils.isEmpty(providerId) || (status != Constant.MERCHANT_GOODS_GROUP_STATUS_1 && status != Constant.MERCHANT_GOODS_GROUP_STATUS_2)){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_GET_ERROR);
            logger.debug("error code：" + ErrorCode.PARAM_GET_ERROR.getCode() + " msg" + ErrorCode.PARAM_GET_ERROR.getMsg());
            return result;
        }

        entity.setStatus(status);
        try {
            baseMapper.update(entity, Wrappers.<GoodsProviderEntity>lambdaQuery().eq(GoodsProviderEntity::getProviderId, providerId));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    public ResultDO otherPage(GoodsProviderQueryDO query) {
        GoodsProviderEntity entity = new GoodsProviderEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, query);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<GoodsProviderEntity> wrapper = new QueryWrapper<GoodsProviderEntity>(entity);
        wrapper.lambda().eq(GoodsProviderEntity::getIsDelete, Constant.IS_DELETE_FALSE);
        if(StringUtils.isNotEmpty(query.getGoodsName())){
            wrapper.lambda().like(GoodsProviderEntity::getGoodsName, query.getGoodsName());
        }
        if(StringUtils.isNotEmpty(query.getProviderName())){
            wrapper.lambda().like(GoodsProviderEntity::getProviderName, query.getProviderName());
        }
        if(StringUtils.isNotEmpty(query.getProviderNo())){
            wrapper.lambda().eq(GoodsProviderEntity::getProviderNo, query.getProviderNo());
        }
        if(StringUtils.isNotEmpty(query.getProviderId())){
            wrapper.lambda().eq(GoodsProviderEntity::getProviderId, query.getProviderId());
        }
        if(query.getStatus() != null){
            wrapper.lambda().eq(GoodsProviderEntity::getStatus, query.getStatus());
        }
        wrapper.lambda().orderByAsc(GoodsProviderEntity::getGoodsId, GoodsProviderEntity::getCostDiscount);
        wrapper.lambda().orderByDesc(GoodsProviderEntity::getPriority);
        Page<GoodsProviderEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        IPage<GoodsProviderEntity> iPage = null;

        try {
            iPage = baseMapper.selectOtherPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        List<GoodsProviderDO> doList = getDomainList(iPage.getRecords());

        PageDO<GoodsProviderDO> pageDO = new PageDO<>();
        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);
        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }


    public ResultDO find(GoodsProviderQueryDO query) {
        GoodsProviderEntity entity = new GoodsProviderEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, query);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<GoodsProviderEntity> wrapper = new QueryWrapper<GoodsProviderEntity>(entity);
        if(StringUtils.isNotEmpty(query.getGoodsName())){
            wrapper.lambda().like(GoodsProviderEntity::getGoodsName, query.getGoodsName());
        }
        if(StringUtils.isNotEmpty(query.getGroupName())){
            wrapper.lambda().like(GoodsProviderEntity::getGroupName, query.getGroupName());
        }
        if(StringUtils.isNotEmpty(query.getProviderName())){
            wrapper.lambda().like(GoodsProviderEntity::getProviderName, query.getProviderName());
        }
        if(query.getGroupId() != null){
            wrapper.lambda().eq(GoodsProviderEntity::getGroupId, query.getGroupId());
        }
        if(query.getProviderId() != null){
            wrapper.lambda().eq(GoodsProviderEntity::getProviderId, query.getProviderId());
        }
        if(query.getHierarchy() != null && query.getHierarchy() == 2){
            wrapper.lambda().groupBy(GoodsProviderEntity::getGroupId,GoodsProviderEntity::getProviderId);
        }
        if(query.getHierarchy() != null && query.getHierarchy() == 3){
            wrapper.lambda().orderByAsc(GoodsProviderEntity::getDenomination);
        }
        Page<GoodsProviderEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());
        IPage<GoodsProviderEntity> iPage = null;

        try {
            iPage = baseMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        List<GoodsProviderDO> doList = getDomainList(iPage.getRecords());

        if(query.getHierarchy() != null && query.getHierarchy() == 2 && doList != null && doList.size() >0){
            //查询这条数据在的旧折扣
            try {
                doList.stream().forEach( item -> {
                    Page<GoodsProviderEntity> queryPage = new Page<>(query.getCurrentPage(),100);
                    QueryWrapper<GoodsProviderEntity> queryWrapper = new QueryWrapper<GoodsProviderEntity>(entity);
                    queryWrapper.lambda().eq(GoodsProviderEntity::getProviderId, item.getProviderId()).eq(GoodsProviderEntity::getGroupId, item.getGroupId());
                    IPage<GoodsProviderEntity> resultData = baseMapper.selectPage(queryPage, queryWrapper);
                    List<GoodsProviderEntity> goodsProviderEntityList = resultData.getRecords();
                    if(goodsProviderEntityList != null && goodsProviderEntityList.size() >0){
                        goodsProviderEntityList.stream().forEach( obj -> {
                            if(item.getAfterCostDiscount() != null && item.getAfterCostDiscount().floatValue() != obj.getCostDiscount().floatValue()){
                                item.setRed(true);
                            }
                        });
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                logger.debug("设置是否显示红色错误");
            }
        }

        PageDO<GoodsProviderDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }
    

	@Override
	public ResultDO list(String goodsId) {

        ResultDO result = new ResultSupport();

        List<GoodsProviderEntity> list = null;

        QueryWrapper<GoodsProviderEntity> wrappers = new QueryWrapper();

        wrappers.lambda().eq(GoodsProviderEntity::getIsDelete, Constant.IS_DELETE_FALSE).eq(GoodsProviderEntity::getGoodsId, goodsId);
        wrappers.lambda().orderByAsc(GoodsProviderEntity::getCostDiscount);
        try {
            list = this.baseMapper.selectList(wrappers);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<GoodsProviderDO> doList = getDomainList(list);

        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
	}

    @Override
    public ResultDO listByProviderId(String providerId) {

        ResultDO result = new ResultSupport();

        List<GoodsProviderEntity> list = null;

        QueryWrapper<GoodsProviderEntity> wrappers = new QueryWrapper();

        wrappers.lambda().eq(GoodsProviderEntity::getIsDelete, Constant.IS_DELETE_FALSE).eq(GoodsProviderEntity::getProviderId, providerId);
        try {
            list = this.baseMapper.selectList(wrappers);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<GoodsProviderDO> doList = getDomainList(list);

        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
    }

    private GoodsDO getDomain(GoodsEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        GoodsDO domain = new GoodsDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private GoodsProviderDO getDomain(GoodsProviderEntity entity) {
        ResultDO result = new ResultSupport();
        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        GoodsProviderDO domain = new GoodsProviderDO();

        if(!result.isSuccess()) {
            return null;
        }
        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<GoodsProviderDO> getDomainList(List<GoodsProviderEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<GoodsProviderDO> doList = new ArrayList<GoodsProviderDO>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(GoodsProviderEntity entity : list) {

                GoodsProviderDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }
    private ResultDO checkDiscount(ResultDO result, List<GoodsDO> goodsList,float costDiscount, int lossType){
        //查询这里商品列表是否在供应商中关联
        List<GoodsMerchantDO> goodsMerchantList = new ArrayList<>();
        try {
            for (GoodsDO goods : goodsList) {
                GoodsMerchantDO findDomain = new GoodsMerchantDO();
                findDomain.setGoodsId(goods.getId());
                ResultDO selectResult = goodsMerchantService.findList(findDomain);
                if(!result.isSuccess()){
                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
                List<GoodsMerchantDO> addList = (List<GoodsMerchantDO>) selectResult.getModel(ResultDO.FIRST_MODEL_KEY);
                if(addList != null && addList.size() >0){
//                    goodsMerchantList.addAll(addList);
                    goodsMerchantList.add(addList.get(0));
                }
            }
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        //判断设置的代理折扣是否能通过供应商设置的亏损方式
        if(goodsMerchantList != null && goodsMerchantList.size() >0){
            for (GoodsMerchantDO obj : goodsMerchantList) {
                if(obj.getLossType() == Constant.LOSS_TYPE_1) continue;
                if(obj.getLossType() == Constant.LOSS_TYPE_0){
                    if(obj.getDiscount().floatValue() >= costDiscount) continue;
                    result.setSuccess(false);
                    ErrorCode errorCode = ErrorCode.GOODS_EDIT_DISCOUNT_ERROR;
                    errorCode.setMsg("折扣过高，亏损范围：不允许亏损可平价。代理折扣:" + obj.getDiscount() * 100 + "%");
                    result.setErrorCode(errorCode);
                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                    return result;
                }
                if(obj.getLossType() == Constant.LOSS_TYPE_2){
                    if(obj.getDiscount().floatValue() > costDiscount) continue;
                    result.setSuccess(false);
                    ErrorCode errorCode = ErrorCode.GOODS_EDIT_DISCOUNT_ERROR;
                    errorCode.setMsg("折扣过高，亏损范围：不允许亏损只能盈利。代理折扣:" + obj.getDiscount() * 100 + "%");
                    result.setErrorCode(errorCode);
                    logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
                    return result;
                }
            }
        }
        return result;
    }

}
